﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

delegate void LogAppend(String Message);

namespace ImageDownloadClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
//            m_downloadLog = new DownloadLog();
  //          m_downloadController = new DownloadController(WritelnLog, 1, m_downloadLog);
            RTB_Log.HideSelection = false;
        }

        public void WritelnLog(String s)
        {
            if (RTB_Log.InvokeRequired)
            {
                LogAppend d = new LogAppend(WritelnLog);
                this.Invoke(d, new object[] { s });
            }
            else
            {
                RTB_Log.AppendText(s + "\n");
                RTB_Log.Focus();
            }
        }

        private void BTN_Start_Click(object sender, EventArgs e)
        {
            if (BTN_Start.Text == "Start")
            {
                String validate = validateInput();
                if (String.IsNullOrEmpty(validate))
                {
                    String url = "http://" + TB_ConnString.Text + "/";
                    m_controller = ImageDownloaderController.getInstance(this.WritelnLog);
                    m_controller.FlyingPig.setConnect(url);
                    m_controller.Concept = this.TB_Concept.Text;
                    m_controller.DownloadFolder = this.TB_Database.Text;
                    m_controller.start();
                    
            /*        if (m_downloadController.getCurStatus() == DownloadController.DownloadStatus.STATUS_STOP)
                    {
                        //尝试连接服务器


                        //得到一个下载
                        String url = TB_ConnString.Text;


                        // 开始
                        m_downloadController.start(TB_Database.Text,
                            //Int32.Parse(TB_StartID.Text),
                                                   1);
                                                   //Int32.Parse(TB_MaxThread.Text));
                        
                        BTN_Start.Text = "Stop";
                        BTN_Concept.Enabled = false;
                        BTN_Database.Enabled = false;

                        // 打开更新计时器
                        timer_Update.Enabled = true;
                    }*/
                }
                else
                {
                    // 提示出错
                    MessageBox.Show(validate, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                BTN_Start.Text = "Start";
                BTN_Database.Enabled = true;
                timer_Update.Enabled = false;
         //       m_downloadController.stop();
            }
        }

        private String validateInput()
        {
            if (String.IsNullOrEmpty(TB_Database.Text))
            {
                return "Missing Image Database Folder!";
            }

            if (String.IsNullOrEmpty(TB_Concept.Text))
            {
                return "Missing Concept List File!";
            }
/*
            try
            {
                int nMax = Int32.Parse(TB_Consumer.Text);
                if (nMax <= 0)
                {
                    return "Invalid Max Download Value!";
                }
            }
            catch (System.Exception)
            {
                return "Invalid Max Download Value!";
            }*/


            return "";
        }

        private void BTN_Database_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                TB_Database.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void BTN_Concept_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                TB_Concept.Text = openFileDialog1.FileName;
            }
        }

        private void timer_Update_Tick(object sender, EventArgs e)
        {
            //LB_Status.Text = "Status: " + conceptInfo;
            //LB_Status.Text = "下载中，下载了" + FinishedSize + "个字节";
        }

        ImageDownloaderController m_controller;

        private void BTN_Pause_Click(object sender, EventArgs e)
        {
            WritelnLog("=============START TO PAUSE, WAIT FOR CUR THREADS FINISHED==============");
            m_controller.pause();
        }

        public String getSubDirectoryByPhotoId(int id)
        {
            const int SEGMENT = 10000;
            int count = id/SEGMENT;
            int offset = id % SEGMENT;

            StringBuilder buffer = new StringBuilder();

            if (count == 0) buffer.Append("\\0-9999\\");
            else buffer.Append(count).Append("\\0000").Append(count).Append("9999\\");

            return buffer.ToString();
        }

        public String getFileNameByPhotoId(int id)
        {
            return id.ToString();
        }

        public void doExecuteLegacy()
        {
            // 获取当前路径下全部文件名
            //String[] files = Directory.GetFiles(Environment.CurrentDirectorry);
            String path = TB_Database.Text;
            String[] files = Directory.GetFiles(path);
            int moved = 0;

            WritelnLog("找到" + files.Length + "个文件");

            foreach (String filename in files)
            {
                // 最后一个"\"
                int lastpath = filename.LastIndexOf("\\");
                // 最后一个"."
                int lastdot = filename.LastIndexOf(".");
                // 纯文件名字长度
                int length = lastdot - lastpath - 1;
                // 文件目录字符串 xx\xx\xx 
                String beginpart = filename.Substring(0, lastpath + 1);
                // 纯文件名字
                String namenoext = filename.Substring(lastpath + 1, length);
                // 扩展名
                String ext = filename.Substring(lastdot);

                // 补齐为3位，组成新的文件名
                String namenew = getSubDirectoryByPhotoId(moved)+getFileNameByPhotoId(moved);
                
                String fullnewname = beginpart + namenew + ext;
                // 改名

                if (!Directory.Exists(beginpart+getSubDirectoryByPhotoId(moved)))
                {
                    Directory.CreateDirectory(beginpart+getSubDirectoryByPhotoId(moved));
                }

                File.Move(filename, fullnewname);

                moved++;

                if (moved % 500 == 0)
                    WritelnLog("移动并改名了" + moved + "//" + files.Length + "个文件");
            }
            WritelnLog("一共移动了" + moved + "个文件");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread legacyProcessThread = new Thread(new ThreadStart(doExecuteLegacy));
            legacyProcessThread.IsBackground = true;
            legacyProcessThread.Start();
        }

        //DownloadLog m_downloadLog;
        //DownloadController m_downloadController;
    }
}
